package com.ezlcp.user.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ezlcp.commons.base.db.BaseService;
import com.ezlcp.commons.base.entity.IUser;
import com.ezlcp.commons.base.entity.JsonResult;
import com.ezlcp.commons.tool.StringUtils;
import com.ezlcp.commons.utils.ContextUtil;
import com.ezlcp.user.entity.Menu;
import com.ezlcp.user.entity.TenantMenu;
import com.ezlcp.user.service.MenuServiceImpl;
import com.ezlcp.user.web.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/ezlcp/user/menu")
@Tag(name = "系统菜单表")
public class MenuController extends BaseController<Menu> {
    @Autowired
    MenuServiceImpl menuService;

    @Operation(summary = "根据前端的路由取对应的菜单名")
    @GetMapping("getMenuName")
    public String getMenuName(@Parameter(description = "前端的路由") @RequestParam String path) {
        return menuService.getMenuName(path);
    }

    @Operation(summary = "a.获取当前用户已授权的菜单")
    @PostMapping("/getUserMenus")
    public JsonResult getUserMenus() {
        IUser user = ContextUtil.getCurrentUser();
        if (user == null) {
            return JsonResult.Fail("menu.firstLogin");
        }
        JsonResult result = JsonResult.Success("menu.success");
        result.setShow(false);
        String userId = user.getUserId();
        String tenantId = user.getTenantId();
        if (user.isPlatformUser()) {
            //超管
            if (user.isAdmin()) {
                result.setData(menuService.getPlatformMenus());
            } else {//平台用户（管理员）
                Object data = menuService.getAdminUserMenus(userId);
                result.setData(data);
            }
        } else {
            //公司管理员
            if (user.isAdmin()) {
                Object data = menuService.getTenantAllMenus(tenantId);
                result.setData(data);
            } else {//普通用户
                Object data = menuService.getCommonUserMenus(userId, tenantId);
                result.setData(data);
            }
        }
        return result;
    }

    @Operation(summary = "b.获取普通用户某个页面中的权限（按钮等）", description = "system或company拥有页面全部权限，可跳过调用本接口")
    @PostMapping("/getUserPageAuth")
    public JsonResult getUserPageAuth(@Parameter(description = "菜单Id")
                                      @RequestParam(value = "menuId") String menuId) {
        IUser user = ContextUtil.getCurrentUser();
        if (user == null) {
            return JsonResult.Fail("menu.firstLogin");
        }
        if (StringUtils.isEmpty(menuId)) {
            return JsonResult.Fail("menu.paramError");
        }
        JsonResult result = JsonResult.Success("menu.success");
        Object data = menuService.getUserPageAuth(user.getUserId(), menuId);
        result.setData(data);
        result.setShow(false);
        return result;
    }

    @Operation(summary = "c.获取当前用户所有可授权菜单")
    @PostMapping("/getAllMenus")
    public JsonResult getAllMenus() {
        IUser user = ContextUtil.getCurrentUser();
        if (user == null) {
            return JsonResult.Fail("menu.firstLogin");
        }
        JsonResult result = JsonResult.Success("menu.success");
        result.setShow(false);
        //管理账号
        if (user.isPlatformUser()) {
            result.setData(menuService.getPlatformMenus());
        } else {
            result.setData(menuService.getTenantAllMenus(user.getTenantId()));
        }
        return result;
    }

    @Operation(summary = "d.获取菜单页面元素（按钮等权限）")
    @PostMapping("/getPageElements")
    public JsonResult getPageElements(@Parameter(description = "菜单Id,不传则查询全部元素")
                                      @RequestParam(value = "menuId", required = false) String menuId) {
        JsonResult result = JsonResult.Success("menu.success");
        result.setShow(false);
        result.setData(menuService.getElements(menuId));
        return result;
    }

    @Operation(summary = "h.获取用户组的授权信息")
    @PostMapping("/getGroupAuthInfo")
    public JsonResult getGroupAuthInfo(@Parameter(description = "用户组Id")
                                       @RequestParam(value = "GroupId") String GroupId) {
        if (StringUtils.isEmpty(GroupId)) {
            return JsonResult.Fail("menu.paramError");
        }
        JsonResult result = menuService.getGroupAuthInfo(GroupId);
        if (result.isSuccess()) {
            logService.saveSystemLog(getComment(), "getGroupAuthInfo", GroupId, null);
        }
        return result;
    }

    @Operation(summary = "f.修改用户组的菜单授权", description = "<font color='red'><b>会先删除该用户组的旧菜单授权，再插入新授权</b></font>" +
            "<br>请求参数示例格式：{\n" +
            "<br>    \"groupId\": \"1\",\n" +
            "<br>    \"auth\": [\n" +
            "<br>        {\n" +
            "<br>            \"menuId\": 111,\n" +
            "<br>            \"hasElement\": \"1\",\n" +
            "<br>            \"elements\": [{\"elementKey\":\"add\",\"elementName\":\"新增\",\"type\": \"button\"}" +
            ",{\"elementKey\":\"edit\",\"elementName\":\"編輯\",\"type\": \"button\"}]\n" +
            "<br>        },\n" +
            "<br>        {\n" +
            "<br>            \"menuId\": 131,\n" +
            "<br>            \"hasElement\": 1,\n" +
            "<br>            \"elements\": []\n" +
            "<br>        }    ]\n" +
            "<br>}" +
            "<br>groupId为用户组ID，menuId为菜单ID一个菜单最多只能有一条记录，hasElement值为（0表求该菜单下面不需要控制按钮权限，否则为1），" +
            "<br>elements为已选择授权的元素数据组[{元素Key,元素名，类型}]")
    @PostMapping("/editGroupMenus")
    public JsonResult editGroupMenus(@RequestBody JSONObject data) {
        String groupId = data.getString("groupId");
        JSONArray auth = data.getJSONArray("auth");
        if (StringUtils.isEmpty(groupId) || auth == null) {
            return JsonResult.Fail("menu.paramError");
        }
        JsonResult result = JsonResult.Success("menu.success");
        result.setShow(false);
        menuService.editGroupMenus(groupId, auth);
        logService.saveSystemLog(getComment(), "Group authorization", groupId, JSON.toJSONString(auth));
        return result;
    }

    @Override
    public JsonResult<Menu> get(@RequestParam(value = "pkId") String pkId) {
        IUser user = ContextUtil.getCurrentUser();
        if (user == null || StringUtils.isEmpty(pkId)) {
            return JsonResult.Fail("menu.paramError");
        }
        JsonResult result = JsonResult.Success("menu.success");
        result.setShow(false);
        String tenantId = user.getTenantId();
        //平台用户
        if (StringUtils.isEmpty(tenantId)) {
            return super.get(pkId);
        }
        //普通用户
        result.setData(menuService.getTenantMenu(pkId, tenantId));
        return result;
    }

    @Operation(summary = "保存修改菜单")
    public JsonResult save(@Parameter(description = "菜单") @RequestBody TenantMenu entity) throws Exception {
        String tenantId = ContextUtil.getCurrentTenantId();
        entity.setSeq(entity.getSeq() + 1);
        //管理员用户
        if (StringUtils.isEmpty(tenantId)) {
            Menu menu = new Menu();
            BeanUtils.copyProperties(entity, menu);
            return super.save(menu, null);
        }
        menuService.updateTenantMenu(entity, tenantId);
        logService.saveSystemLog(getComment(), "update TenantMenu", entity.getMenuId(), JSON.toJSONString(entity));
        return JsonResult.getSuccessResult("menu.success");
    }

    @Operation(summary = "【已关闭】根据主键ID删除记录")
    @Override
    public JsonResult del(String ids) {
        return JsonResult.getSuccessResult("menu.portClose");
    }

    @Override
    public BaseService getBaseService() {
        return menuService;
    }

    @Override
    public String getComment() {
        return "系统菜单表";
    }
}